package midone.exchangeskill.base.view;

import android.annotation.TargetApi;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.readystatesoftware.systembartint.SystemBarTintManager;


import midone.exchangeskill.R;
import midone.exchangeskill.base.dagger.AppComponent;
import midone.exchangeskill.utils.RxBus;
import midone.exchangeskill.utils.ScreenManager;
import midone.exchangeskill.utils.StringUtils;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.subscriptions.CompositeSubscription;


public abstract class BaseActivity extends AppCompatActivity {
    boolean onDestroyed;//是否已经onDestroy
    private CompositeSubscription mCompositeSubscription;

    public boolean isOnDestroyed() {
        return onDestroyed;
    }

    AlertDialog.Builder builder;
    public int screenHeight;
    public int screenWidth;

    protected abstract void setUpComponent(AppComponent appComponent);


    @Override
    protected void onResume() {
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        super.onResume();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        rxBusObservers();
        ScreenManager.getScreenManager().pushActivity(this);
        setUpComponent(Application.getApplication().getAppComponent());
    }

    ViewGroup rootView;

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        super.setContentView(layoutResID);
        rootView = (ViewGroup) ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
        rootView.setFitsSystemWindows(true);
        rootView.setClipToPadding(true);
    }


    private void initSystemBar(int statusBarColor) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            if (Build.VERSION.SDK_INT >= 21) fixMStatusBar(statusBarColor);
        }
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setNavigationBarTintEnabled(true);
        tintManager.setTintColor(statusBarColor);
    }

    /**
     * 更改狀態欄顔色
     *
     * @param statusBarColor
     */
    public void setTintColor(int statusBarColor) {
        initSystemBar(statusBarColor);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void fixMStatusBar(int statusBarColor) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().setStatusBarColor(statusBarColor);// SDK21
    }

    public int getScreenWidth() {
        return screenWidth;
    }


    public int getScreenHeight() {
        return screenHeight;
    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }


    public void showToastMessage(String msg, View view) {
        if (msg == null) {
            return;
        }
        Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setView(view);
        toast.show();

    }

    /**
     * 是否为空
     *
     * @param str
     * @return
     */
    public boolean isEmpty(String str) {
        return StringUtils.isEmpty(str);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }


    /**
     * Activity，dialog的布局
     *
     * @param dialogView
     * @return
     */
    public AlertDialog showDialog(View dialogView, WindowManager.LayoutParams layoutParams) {
        if (builder == null) {
            builder = new AlertDialog.Builder(this);
        }
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(dialogView);
        if (layoutParams == null) {
            layoutParams = window.getAttributes();
            layoutParams.width = screenWidth;
            layoutParams.gravity = Gravity.BOTTOM;
        }
        window.setAttributes(layoutParams);
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        return alertDialog;
    }

    public AlertDialog showCenterDialog(View dialogView) {
        if (builder == null) {
            builder = new AlertDialog.Builder(this);
        }
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(dialogView);
        return alertDialog;
    }

    public void showSnackBar(String msg) {
        if (isEmpty(msg)) return;
        Snackbar.make(rootView, msg, Snackbar.LENGTH_SHORT).show();
    }


    /**
     * 带action 按钮的snackBar
     *
     * @param msg
     * @param action
     * @param onClickListener
     */
    public void showSnackBar(String msg, String action, View.OnClickListener onClickListener) {
        if (isEmpty(msg)) return;
        Snackbar snackbar = Snackbar.make(rootView, msg, Snackbar.LENGTH_INDEFINITE).setAction(action, onClickListener);
        TextView textView = (TextView) snackbar.getView().findViewById(R.id.snackbar_action);
//        textView.setTextColor(getResources().getColor(R.color.nekoneko_swipeColor));
        snackbar.show();
    }


    @Override
    protected void onDestroy() {
        if (mCompositeSubscription != null) {
            mCompositeSubscription.unsubscribe();//取消注册，以避免内存泄露
            mCompositeSubscription.clear();
            mCompositeSubscription = null;
        }
        onDestroyed = true;
        ScreenManager.getScreenManager().popActivity(this);
        super.onDestroy();
    }


    /**
     * 订阅消息
     */
    private void rxBusObservers() {
        Subscription subscription = RxBus.getInstance().toObserverable().observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Object>() {
            @Override
            public void call(Object event) {
                if (event instanceof RxBus.RxMessageEvent) {
                    //do something
                    onRxBusMessageEvent((RxBus.RxMessageEvent) event);
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                throwable.printStackTrace();
            }
        });
        addSubscription(subscription);
    }

    /**
     * ·
     * rx订阅消息
     *
     * @param rxMessageEvent
     */
    protected void onRxBusMessageEvent(RxBus.RxMessageEvent rxMessageEvent) {
    }

    /**
     * 把订阅添加到CompositeSubscription
     *
     * @param subscription
     */
    public void addSubscription(Subscription subscription) {
        if (subscription == null) {
            return;
        }
        if (this.mCompositeSubscription == null) {
            this.mCompositeSubscription = new CompositeSubscription();
        }

        this.mCompositeSubscription.add(subscription);
    }
}
